﻿using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Windows;
using System.Runtime.InteropServices;

namespace Messenger
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static Mutex mutex = null;
        protected override void OnStartup(StartupEventArgs e)
        {
            const string appName = "MyStudyApp";

            mutex = new Mutex(true, appName, out bool createdNew);
            if (!createdNew) //已经有单例实例在运行，激活已有实例并退出当前实例。
            {
                Process current = Process.GetCurrentProcess();
                foreach(Process process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id) 
                    {
                        //激活已有实例的主窗口
                        NativeMethods.SetForegroundWindow(process.MainWindowHandle);
                        break;
                    }
                }
                Shutdown();
            }
            else
            {
                base.OnStartup(e);
            }
        }
        protected override void OnExit(ExitEventArgs e)
        {
            mutex?.ReleaseMutex();
            base.OnExit(e);
        }
    }
    internal static class NativeMethods
    {
        [DllImport("user32.dll")]
        [return:MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hwnd);
    }

}
